package com.demo.delivery;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;

public class GetJsonTask extends AsyncTask<Void, Void, JSONObject> {
	private String URL;
	private JSONObject jsonObjSend;

	public GetJsonTask(String URL, JSONObject jsonObjSend) {
		this.URL = URL;
		this.jsonObjSend = jsonObjSend;
	}

	public static String convertStreamToString(java.io.InputStream is) {
		java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
		return s.hasNext() ? s.next() : "";
	}

	@Override
	protected JSONObject doInBackground(Void... params) {
		JSONObject jsonObjRecv = null;
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPut httpPutRequest = new HttpPut(URL);

			StringEntity se;
			se = new StringEntity(jsonObjSend.toString());

			// Set HTTP parameters
			httpPutRequest.setEntity(se);
			httpPutRequest.setHeader("Accept", "application/json");
			httpPutRequest.setHeader("Content-type", "application/json");
			String base64EncodedCredentials = "Basic " + Base64.encodeToString( 
                    ("admin" + ":" + "secret").getBytes(), 
                    Base64.NO_WRAP);


			httpPutRequest.setHeader("Authorization", base64EncodedCredentials);
			long t = System.currentTimeMillis();
			HttpResponse response = (HttpResponse) httpclient
					.execute(httpPutRequest);

			HttpEntity entity = response.getEntity();

			if (entity != null) {
				// Read the content stream
				InputStream instream = entity.getContent();

				// convert content stream to a String
				String resultString = convertStreamToString(instream);
				instream.close();
				// resultString =
				// resultString.substring(1,resultString.length()-1); // remove
				// wrapping "[" and "]"

				// jsonObjRecv = new JSONObject(resultString);

				// Raw DEBUG output of our received JSON object:
				// Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObjRecv;
	}

	protected void onPostExecute(JSONObject result) {

	}

}